<?php get_header(); ?>

<!-- 主内容区 -->
<main class="container mx-auto px-4 sm:px-6 lg:px-8 pt-24 pb-12 flex-grow">
    <?php
    $show_carousel = wanzi_option('g_carousel');
    $carousel_items = wanzi_option('carousel_group');

    if ($show_carousel && !empty($carousel_items)) :
    ?>
        <section class="mb-12">
            <!-- Slider main container -->
            <div class="swiper h-[400px] rounded-xl">
                <!-- Additional required wrapper -->
                <div class="swiper-wrapper">
                    <!-- Slides -->
                    <?php foreach ($carousel_items as $item) : ?>
                        <div class="swiper-slide relative">
                            <img src="<?php echo esc_url($item['c_img']); ?>" alt="<?php echo esc_attr($item['c_title']); ?>" class="w-full h-full object-cover">
                            <a href="<?php echo esc_url($item['c_url']); ?>" target="_blank" rel="noopener noreferrer" class="absolute inset-0 bg-black bg-opacity-40 flex flex-col justify-end p-6">
                                <?php if (!empty($item['c_title'])) : ?>
                                    <h2 class="text-2xl font-bold mb-2" style="color: <?php echo esc_attr($item['c_color']); ?>;"><?php echo esc_html($item['c_title']); ?></h2>
                                <?php endif; ?>
                                <?php if (!empty($item['c_subtitle'])) : ?>
                                    <p class="text-base" style="color: <?php echo esc_attr($item['c_color']); ?>;"><?php echo esc_html($item['c_subtitle']); ?></p>
                                <?php endif; ?>
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
                <!-- If we need pagination -->
                <div class="swiper-pagination"></div>

                <!-- If we need navigation buttons -->
                <div class="swiper-button-prev"></div>
                <div class="swiper-button-next"></div>
            </div>
        </section>
    <?php else : ?>
    <!-- 头条区域 -->
    <section class="mb-12">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <?php
            $sticky = get_option('sticky_posts');
            rsort($sticky);
            $sticky = array_slice($sticky, 0, 3);
            $query = new WP_Query(array('post__in' => $sticky, 'ignore_sticky_posts' => 1));
            $first_post = true;
            $counter = 0;
            if ($query->have_posts()) :
                while ($query->have_posts()) : $query->the_post();
                    if ($first_post) :
                        $first_post = false;
            ?>  
                        <!-- 主要头条 -->
                        <div class="lg:col-span-2 relative rounded-xl overflow-hidden group h-[400px] animate-fade-in">
                            <?php if (has_post_thumbnail()) : ?>  
                                <img src="<?php the_post_thumbnail_url('full'); ?>" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                            <?php else : ?>  
                                <?php $first_img = get_first_image_from_content();
                                if ($first_img) : ?>  
                                    <img src="<?php echo esc_url($first_img); ?>" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                <?php else : ?>  
                                    <img src="https://picsum.photos/800/400" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                <?php endif; ?>  
                            <?php endif; ?>  
                            <div class="absolute inset-0 article-gradient flex flex-col justify-end p-6">
                                <?php $category = get_the_category();
                                if ($category) : ?>  
                                    <span class="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-primary/90 text-white mb-3 w-max"><?php echo esc_html($category[0]->name); ?></span>
                                <?php endif; ?>  
                                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-white mb-2 leading-tight"><a href="<?php the_permalink(); ?>" class="text-white hover:underline"><?php the_title(); ?></a></h2>
                                <p class="text-white/90 mb-4 max-w-2xl"><?php echo wp_trim_words(get_the_content(), 20, '...'); ?></p>
                                <div class="flex items-center">
                                    <div class="ml-0">
                                        <p class="text-white text-sm font-medium"><?php the_author(); ?></p>
                                        <p class="text-white/70 text-xs"><?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . '前'; ?> · <?php echo round(str_word_count(strip_tags(get_the_content())) / 200) . '分钟阅读'; ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 gap-6">
                        <?php else : 
                            if ($counter < 2) :
                        ?>  
                            <!-- 次要头条 -->
                            <div class="relative rounded-xl overflow-hidden group h-[192px] animate-fade-in" style="animation-delay: 0.1s">
                                <?php if (has_post_thumbnail()) : ?>  
                                    <img src="<?php the_post_thumbnail_url('full'); ?>" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                <?php else : ?>  
                                    <?php $first_img = get_first_image_from_content();
                                    if ($first_img) : ?>  
                                        <img src="<?php echo esc_url($first_img); ?>" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                    <?php else : ?>  
                                        <img src="https://picsum.photos/400/200" alt="<?php the_title_attribute(); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                    <?php endif; ?>  
                                <?php endif; ?>  
                                <div class="absolute inset-0 article-gradient flex flex-col justify-end p-5">
                                    <?php $category = get_the_category();
                                    if ($category) : ?>  
                                        <span class="inline-block px-2 py-1 rounded-full text-xs font-semibold bg-secondary/90 text-white mb-2 w-max"><?php echo esc_html($category[0]->name); ?></span>
                                    <?php endif; ?>  
                                    <h3 class="text-lg font-bold text-white mb-1 leading-tight"><a href="<?php the_permalink(); ?>" class="text-white hover:underline"><?php the_title(); ?></a></h3>
                                    <div class="flex items-center">
                                        <p class="text-white/80 text-xs ml-0"><?php the_author(); ?> · <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . '前'; ?></p>
                                    </div>
                                </div>
                            </div>
                        <?php 
                                $counter++;
                            endif;
                        endif;
                endwhile;
            endif;
            wp_reset_postdata(); ?>
                        </div>
        </div>
    </section>
    <?php endif; ?>
    <section class="mb-10 animate-slide-up">
        <div class="flex overflow-x-auto pb-4 scrollbar-hide space-x-2">
            <?php
            echo '<button data-category="0" class="px-4 py-2 bg-primary text-white rounded-full whitespace-nowrap transition-colors active">全部</button>';
            $categories = get_categories();
            foreach ($categories as $category) {
                echo '<button data-category="' . $category->term_id . '" class="px-4 py-2 bg-white text-neutral-600 rounded-full whitespace-nowrap">
                    ' . esc_html($category->name) . '
                </button>';
            }
            ?>
        </div>
    </section>
    <!-- 主要内容区 -->
    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <!-- 文章列表 -->
        <div class="lg:col-span-8 space-y-8">
            <!-- 文章列表容器 -->
            <div id="posts-container" class="lg:col-span-8 space-y-8">
                <!-- 文章将通过 AJAX 动态加载 -->
            </div>
            <button id="load-more" class="mt-8 mx-auto block px-6 py-3 bg-blue-500 text-white rounded hover:bg-blue-600">加载更多</button>
        </div>

        <?php include('sidebar.php'); ?>
    </div>
</main>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const postsContainer = document.querySelector('#posts-container');
        const categoryButtons = document.querySelectorAll('button[data-category]');
        const loadMoreButton = document.querySelector('#load-more');
        let currentPage = 1;
        let currentCategory = 0;

        function setActiveButton(button) {
            categoryButtons.forEach(btn => {
                btn.classList.remove('active');
                btn.classList.add('bg-white', 'text-neutral-600');
                btn.classList.remove('bg-primary', 'text-white');
            });
            button.classList.add('active');
            button.classList.remove('bg-white', 'text-neutral-600');
            button.classList.add('bg-primary', 'text-white');
        }

        function loadPosts(categoryId, page = 1, isAppend = false) {
            currentCategory = categoryId;
            if (!isAppend) {
                currentPage = 1;
            }
            let url = `<?php echo admin_url("admin-ajax.php"); ?>?action=load_posts_by_term&page=${page}&term_id=${categoryId}`;
            if (categoryId > 0) {
                 url += '&is_category=1';
            }
            
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);

            xhr.onload = function() {
                if (xhr.status === 200) {
                    if (isAppend) {
                        postsContainer.innerHTML += xhr.responseText;
                    } else {
                        postsContainer.innerHTML = xhr.responseText;
                    }
                    if (xhr.responseText.trim()) {
                        currentPage++;
                        loadMoreButton.style.display = 'block';
                    } else {
                        loadMoreButton.style.display = 'none';
                    }
                }
            };
            xhr.send();
        }

        categoryButtons.forEach(button => {
            button.addEventListener('click', function() {
                const categoryId = this.getAttribute('data-category');
                setActiveButton(this);
                loadPosts(categoryId);
            });
        });

        loadMoreButton.addEventListener('click', function() {
            loadPosts(currentCategory, currentPage, true);
        });

        // 初始加载全部文章
        loadPosts(0);
    });
</script>

<script src="<?php echo get_template_directory_uri(); ?>/assets/js/swiper-bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const swiper = new Swiper('.swiper', {
            // Optional parameters
            loop: true,
            autoplay: {
                delay: 3000,
            },

            // If we need pagination
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },

            // Navigation arrows
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
    });
</script>

<?php get_footer(); ?>